package com.bxm.springboot.test.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
public class JSLoadeController {

    @RequestMapping("/a.js")
    public void aJs(HttpServletResponse response) throws Exception{
        File file = org.springframework.util.ResourceUtils.getFile("classpath:a.js");
        // 2.获取要下载的文件名

        String fileName = "a.js";

        // 3.设置content-disposition响应头控制浏览器以下载的形式打开文件

        response.setHeader("content-disposition", "attachment;filename=" + fileName);

        // 4.根据文件路径获取要下载的文件输入流
        try {
            InputStream in = new FileInputStream(file);
            int len = 0;
            // 5.创建数据缓冲区
            byte[] buffer = new byte[1024];
            // 6.通过response对象获取OutputStream流
            OutputStream out = response.getOutputStream();
            // 7.将FileInputStream流写入到buffer缓冲区
            while ((len = in.read(buffer)) > 0) {
                // 8.使用OutputStream将缓冲区的数据输出到客户端浏览器
                out.write(buffer, 0, len);
            }
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("/b.js")
    public void bJs(HttpServletResponse response) throws Exception{
        File file = org.springframework.util.ResourceUtils.getFile("classpath:b.js");
        // 2.获取要下载的文件名

        String fileName = "b.js";

        // 3.设置content-disposition响应头控制浏览器以下载的形式打开文件

        response.setHeader("content-disposition", "attachment;filename=" + fileName);

        // 4.根据文件路径获取要下载的文件输入流
        try {
            InputStream in = new FileInputStream(file);
            int len = 0;
            // 5.创建数据缓冲区
            byte[] buffer = new byte[1024];
            // 6.通过response对象获取OutputStream流
            OutputStream out = response.getOutputStream();
            // 7.将FileInputStream流写入到buffer缓冲区
            while ((len = in.read(buffer)) > 0) {
                // 8.使用OutputStream将缓冲区的数据输出到客户端浏览器
                out.write(buffer, 0, len);
            }
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
